package com.lqd.mall.basis.exception;


 
import com.google.common.collect.ImmutableMap;
import com.lqd.mall.basis.code.CommonCode;
import com.lqd.mall.basis.code.ResultCode;
import com.lqd.mall.basis.response.CommonResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.text.ParseException;

@Log4j2
@RestControllerAdvice
public class ExceptionCatch {

   /**
     * 不可变的map
     */
    private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS ;
    /**
     * 创建一个map保存统一异常处理
     */
    private static  ImmutableMap.Builder<Class<? extends Throwable>,ResultCode> builder = ImmutableMap.builder();
    static {
        //在这里加入一些基础的异常类型判断
        /**
         * HttpMessageNotReadableException 调用方在以post json方式请求服务时，没有对参数进行json序列化。
         */
        builder.put(HttpMessageNotReadableException.class, CommonCode.INVALIDPARAM);
        //日期转换失败
        builder.put(ParseException.class,CommonCode.DATE_CONVERSION_FAILURE);
        //数据为空
        builder.put(IllegalArgumentException.class, CommonCode.DATA_IS_EMPTY);

    }

    /**
     * @ExceptionHandler异常统一处理
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public CommonResult customException(CustomException e){
        log.error("catch exeption : "+e.getMessage()+"\r\nexception:" + e);
        return new CommonResult( e.getResultCode());
    }

    @ExceptionHandler(Exception.class)
    public CommonResult exception(Exception e){
        log.error("catch exeption : {}\t\nexception:",e.getMessage(),e);
        if(EXCEPTIONS == null){
            EXCEPTIONS = builder.build();
        }
        ResultCode resultCode = EXCEPTIONS.get(e.getClass());
        return resultCode != null ? new CommonResult(resultCode) : new CommonResult(CommonCode.SERVER_ERROR);
    }
}
